<?php

/**
 * 微信平台 入口
 * 
 * /Apps/Wechat/Controller/ApiController.class.php
 * @author Zix 
 * @version v1.0
 */

namespace Wechat\Controller;

use Think\Controller;
use Common\Service\WechatSdkService;

class ApiController extends Controller {

  var $mer_id;   //商户ID
  var $wx_id;    //微信ID
  var $WechatSdk = null ;  
  var $type;     //消息类型
  var $openid;   //当前用户openid
  
  var $event_list = array(
    'Vote' , 'Shake'
  );
  
  var $debug = FALSE ;  //调试模式

  public function index() {
    $mer_id = I('get.mer_id', '');
    $wx_id = I('get.wx_id', '');

    if (!$wx_id || !$mer_id) {
      die('error param');
    }

    $this->mer_id = $mer_id;
    $this->wx_id = $wx_id;

    $this->WechatSdk = new WechatSdkService($mer_id, $wx_id);

    //微信服务器验证
    $this->WechatSdk->valid();

    //取用户openID
    $this->openid = $this->WechatSdk->getRev()->getRevFrom();
    $this->_log('openid', $this->openid);

    //取消息类型
    $this->type = $this->WechatSdk->getRevType();

    switch ($this->type) {
      case WechatSdkService::MSGTYPE_TEXT:
        $this->_text();
        break;
      case WechatSdkService::MSGTYPE_EVENT:
        //getRevEvent
        $this->_event();
        break;
      case WechatSdkService::MSGTYPE_IMAGE:
        break;
      default:
        $this->WechatSdk->text("What Can I Help With?")->reply();
    }
  }

  /**
   * 处理普通消息
   */
  function _text() {
    $keyword = $this->WechatSdk->getRevContent();
    $this->_response_keyword($keyword);
  }

  /**
   * 处理事件消息
   */
  function _event() {
    $event = $this->WechatSdk->getRevEvent();
    $this->_log('event', $event['event']);
    $this->_log('key', $event['key']);
    switch ($event['event']) {
      case WechatSdkService::EVENT_SUBSCRIBE :
        //订阅事件处理
        $this->_subscribe($event);
        break;
      case WechatSdkService::EVENT_UNSUBSCRIBE:
        //退订
        $this->_unsubscribe();
        break;
      case WechatSdkService::EVENT_MENU_CLICK;
        $keyword = $event['key'];
        $this->_response_keyword($keyword);
        break;
    }
    echo '';
  }

  /**
   * 微信号订阅
   */
  function _subscribe($event) {
    //是否有推荐用户
    $this->_log('event', $event );
    if ( isset($event['key']) && !empty( $event['key'] ) ) {
      $arr = explode('_', $event['key']);
      $pid = $arr[1];
    } else {
      $pid = 0 ;
    }
    $userinfo = $this->WechatSdk->getUserInfo( $this->openid );
    $this->_log('参数1', $this->mer_id .'---' . $this->wx_id );
    $this->_log('参数2', $userinfo );
    $this->_log('参数3', $pid);

    //创建用户
    $MerUser = \Common\Service\MerUserService::instance();
    $ret = $MerUser->create_by_wechat($this->mer_id, $this->wx_id , $userinfo , $pid);

    
    $this->_log('创建' , $ret);
    //取关注 信息
    $this->_response_keyword('subscribe');
  }

  /**
   * 微信号退订
   */
  function _unsubscribe() {
    //退订
    $MerUser = \Common\Service\MerUserService::instance();
    $this->_log('取消关注' , $this->mer_id . '--'.$this->wx_id. '--'. 'wechat'. '--'. $this->openid);
    $MerUser->unfollow_openid($this->mer_id, $this->wx_id, 'wechat', $this->openid);
  }

  //相应关键字
  function _response_keyword($keyword) {
    if ($keyword == 'subscribe') {
      //订阅信息
      $WxTextReply = \Common\Service\WxTextReplyService::instance();
      $text = $WxTextReply->get_by_subscribe($this->wx_id);
      $this->_log('text', $text);
      $this->WechatSdk->text($text)->reply();
    } else {
      //查询文本回复
      $WxTextReply = \Common\Service\WxTextReplyService::instance();
      $text = $WxTextReply->get_content_by_keyword($this->wx_id, $keyword);

      if (!empty($text)) {
        $this->_log('text', $text);
        $this->WechatSdk->text($text)->reply();
      }

      //查询图文回复
      $WxNewsReply = \Common\Service\WxNewsReplyService::instance();
      $news = $WxNewsReply->get_by_keyword($this->wx_id, $keyword);
      if (!empty($news)) {
        $this->_log('text', print_r($news, TRUE));
        $this->WechatSdk->news($news)->reply();
      }
      
      //查询活动
      foreach ( $this->event_list as $row ) {
        $service = "\Common\Service\WxEvent".$row."Service";
        $EventInstance = $service::instance();
        $search_data = $EventInstance->get_by_keyword($this->wx_id , $keyword);
        if (!empty($search_data)) {
          //$this->_log('text', print_r($news, TRUE));
          $this->WechatSdk->news($search_data)->reply();
          return ;
        }
      }
    }
    
    $text = 'SUCCESS' . "\r\n" ;
    $this->_log('reply', $text );
    echo $text ;
  }

  /**
   * 记录Log文件
   * @param type $key   键
   * @param type $value 值
   */
  function _log($key, $value = '') {
    if ( $this->debug ) {
      $filepath = './Public/logs/wechat.txt';
      if (is_array($value) ) {
        $value = print_r( $value , TRUE );
      }
      $content = date('Y-m-d H:i:s') . " ----> $key = $value \r\n";
      file_put_contents($filepath, $content, FILE_APPEND);
    }
  }
 
  function test() {
    //oVj39t5ylPa56n8vYA29M2yxd7j0
    
    /*
    $version = curl_version();
    print_r($version );
     * 
     */
    
    $WechatPay = new \Common\Service\WechatPayService(1,26);
    $ret = $WechatPay->send_redpack('oVj39t5ylPa56n8vYA29M2yxd7j0', 1 );
    
    if ( $ret ) {
      echo '成功';
    } else {
      echo '失败' . '<br>';
      echo $WechatPay->error_info ;
    }

  }
  
  function test2() {
    $arr  = curl_version();
    print_r( $arr );
  }
  
  

}
